<!--
 * @Date: 2025-05-06 13:40:51
 * @LastEditors: Csir 2215995096@qq.com
 * @LastEditTime: 2025-06-30 09:49:38
 * @FilePath: \yujin-ui-admin\src\views\opticore\materialplan\components\MaterialRecordForm.vue
-->
<template>
  <el-form
    v-if="materialLs.length > 0"
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    class=""
  >
    <div class="containers">
      <div class="tabs">
        <div
          :class="['item', selId === item.id ? 'active' : '']"
          v-for="(item, index) in materialLs"
          :key="index"
          @click="handleSelect(item)"
        >
          <el-tooltip
            class="box-item"
            effect="dark"
            :content="`${item.itemName} (${item.requiredQty})`"
            placement="right"
          >
            {{ `${item.itemName} (${item.requiredQty})` }}
          </el-tooltip>
        </div>
      </div>
      <div class="table">
        <el-table :data="formData" border width="100%" :height="props.type ? 500 : 540">
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column label="序列号" width="230">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="`${$index}.serialNo`"
                :rules="formRules.serialNo"
                class="mb-0px!"
              >
                <el-input
                  v-if="props.type"
                  v-model="row.serialNo"
                  :placeholder="'序列号自动生成'"
                  :disabled="true"
                />
                <div v-else> {{ row.serialNo }}</div>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="位置">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="`${$index}.location`"
                :rules="formRules.location"
                class="mb-0px!"
              >
                <el-input v-if="props.type" v-model="row.location" :disabled="!row.isNew" />
                <div v-else>{{ row.location }}</div>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="纤盘号">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="`${$index}.fiberPalletNo`"
                :rules="formRules.fiberPalletNo"
                class="mb-0px!"
              >
                <el-input v-if="props.type" v-model="row.fiberPalletNo" :disabled="!row.isNew" />
                <div v-else>{{ row.fiberPalletNo }}</div>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="批次号">
            <template #default="{ row, $index }">
              <el-form-item :prop="`${$index}.batchNo`" :rules="formRules.batchNo" class="mb-0px!">
                <el-input v-if="props.type" v-model="row.batchNo" :disabled="!row.isNew" />
                <div v-else> {{ row.batchNo }}</div>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="数量">
            <template #default="{ row, $index }">
              <el-form-item :prop="`${$index}.qty`" :rules="formRules.qty" class="mb-0px!">
                <el-input v-if="props.type" v-model="row.qty" :disabled="!row.isNew" />
                <div v-else> {{ row.qty }}</div>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="领用日期">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="`${$index}.issueDate`"
                :rules="formRules.issueDate"
                class="mb-0px!"
              >
                <el-date-picker
                  v-if="props.type"
                  v-model="row.issueDate"
                  type="date"
                  value-format="x"
                  :disabled="!row.isNew"
                />

                <div v-else> {{ getTime(row.issueDate) }}</div>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="领用人">
            <template #default="{ row, $index }">
              <el-form-item :prop="`${$index}.issuer`" :rules="formRules.issuer" class="mb-0px!">
                <el-autocomplete
                  v-if="props.type"
                  v-model="row.issuer"
                  :fetch-suggestions="querySearchAsync"
                  :disabled="!row.isNew"
                />
                <div v-else> {{ row.issuer }}</div>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" v-if="props.type" label="操作" width="200">
            <template #default="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                v-if="!row.serialNo"
                @click="handleDelete($index)"
                >撤销</el-button
              >
              <!-- <el-button v-else link>—</el-button> -->
              <el-button type="danger" size="small" v-if="row.serialNo" @click="printCode(row)"
                >打印</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row class="mt-3">
          <el-button
            @click="handleAdd"
            style="background-color: #536dfe; color: #fff"
            round
            v-if="props.type"
            >添加一行</el-button
          >
          <el-button
            @click="handleSave"
            style="background-color: #536dfe; color: #fff"
            round
            v-if="props.type"
            >保存</el-button
          >
        </el-row>
      </div>
    </div>
  </el-form>
  <!-- 调用打印组件 -->
  <PrintQrCode
    :visible="printDialogVisible"
    :currentMaterialsItem="selectedMaterialsItem"
    @reset="resetState"
  />
</template>
<script setup lang="ts">
import { MaterialPlanApi } from '@/api/opticore/materialplan'
import { onMounted } from 'vue'
import { userListApi } from '@/api/common'
import type { TabsInstance } from 'element-plus'
import PrintQrCode from '@/views/opticore/print/components/PrintQrCode.vue'
const tabPosition = ref<TabsInstance['tabPosition']>('left')

const props = defineProps<{
  // materialId: undefined
  planNo: undefined
  // orderQuantity: undefined
  // materialOrder: undefined
  // associatedOrder: undefined
  type: Boolean
  docNo: undefined
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  issueDate: [{ required: true, message: '领用日期不能为空', trigger: 'blur' }],
  issuer: [{ required: true, message: '领用人不能为空', trigger: 'blur' }],
  qty: [{ required: true, message: '数量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const userList = ref([])

const getTime = (time) => {
  let date = new Date(time)
  let year = date.getFullYear()
  let month = date.getMonth() + 1 // getMonth()返回的是0-11，所以要加1
  let day = date.getDate()
  return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)
}

onMounted(() => {
  getUserRoleList()
  getList()
})

// watch([() => props.docNo, () => props.planNo], () => {
//   getList()
// })

const materialLs = ref([]) // 列表的数据
const getList = async () => {
  console.log(1112, props)

  const data = await MaterialPlanApi.getMaterialPlanPage({
    pageNo: 1,
    pageSize: 9999,
    planNo: props.planNo,
    docNo: props.docNo
  })
  materialLs.value = data.list
  if (materialLs.value.length > 0) {
    selId.value = materialLs.value[0].id
    getSerialList(materialLs.value[0].id)
  }

  if (data.list.length > 0) {
    getSerialList(data.list[0].id)
    selitem.value = data.list[0]
  }
}

const getList1 = async (params) => {
  const data = await MaterialPlanApi.getMaterialPlanPage({
    pageNo: 1,
    pageSize: 9999,
    planNo: params.planNo,
    docNo: params.docNo
  })
  materialLs.value = data.list
  if (materialLs.value.length > 0) {
    selId.value = materialLs.value[0].id
    getSerialList(materialLs.value[0].id)
  }

  if (data.list.length > 0) {
    getSerialList(data.list[0].id)
    selitem.value = data.list[0]
  }
}

const selId = ref('')
const selitem = ref({})

const handleSelect = (item) => {
  selId.value = item.id
  selitem.value = item

  getSerialList(item.id)
}

const getSerialList = async (val) => {
  formData.value = []
  try {
    formLoading.value = true
    formData.value = await MaterialPlanApi.getMaterialRecordListByMaterialId(val)
  } finally {
    formLoading.value = false
  }
}

/** 监听主表的关联字段的变化，加载对应的子表数据 */

const getUserRoleList = async () => {
  const res = await userListApi({
    pageNo: 1,
    pageSize: 10
  })
  userList.value = res.list
}

const querySearchAsync = (queryString: string, callback: Function) => {
  if (!queryString) {
    callback([])
    return
  }
  const results = userList.value
    .filter((item) => item.username?.includes(queryString))
    .map((item) => ({
      value: item.username,
      ...item
    }))

  callback(results)
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    materialId: undefined,
    serialNo: undefined,
    location: undefined,
    fiberPalletNo: undefined,
    qty: undefined,
    batchNo: undefined,
    /* 获取当前时间的时间戳 */
    issueDate: new Date().getTime(),
    /* 获取当前登录人 */
    issuer: JSON.parse(localStorage.getItem('userInfo')).nickname,
    isNew: true // 新记录标记
  }
  row.materialId = props.materialId
  formData.value.push(row)
}

const handleSave = async () => {
  // 校验表单
  await formRef.value.validate()
  // 深拷贝formData，避免修改原始数据
  const formDataCopy = JSON.parse(JSON.stringify(formData.value))

  // 遍历列表，将每个对象的issueDate转换为时间戳
  formDataCopy.forEach((item) => {
    if (item.issueDate) {
      // 使用getTime()方法将Date对象转换为时间戳
      item.issueDate = new Date(item.issueDate).getTime()
    }
  })

  let data = {
    id: selitem.value.id,
    materialRecords: formDataCopy
  }

  const res = await MaterialPlanApi.updateMaterialPlan(data)

  if (res) {
    getSerialList(selitem.value.id)
  }
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

/** 打印方法 */
const printDialogVisible = ref(false)
const selectedMaterialsItem = ref<any>({})
const printCode = (item: any) => {
  selectedMaterialsItem.value = item
  printDialogVisible.value = true
}

function resetState() {
  printDialogVisible.value = false
}

defineExpose({ validate, getData, getList, getList1, materialLs })
</script>

<style scoped lang="less">
.containers {
  display: flex;
  width: 100%;
  padding: 20px;
  color: #666;
  background-color: #fff;

  .tabs {
    height: 540px;
    overflow-y: auto;
    margin-right: 10px;
    background-color: #f0f2f5;

    .item {
      width: 180px;
      height: 40px;
      line-height: 40px;
      text-align: left;
      padding: 0 30px;
      cursor: pointer;
      color: #909399;
      overflow: hidden;
      /*禁止换行*/
      white-space: nowrap;
      /*显示省略号*/
      text-overflow: ellipsis;
    }

    .active {
      background-color: #536dfe;
      color: #fff;
    }
  }

  .table {
    flex: 1;
  }
}
</style>
